package cn.itsource.blog.service.impl;

import cn.itsource.blog.domain.ArticleType;
import cn.itsource.blog.mapper.ArticleTypeMapper;
import cn.itsource.blog.service.IArticleTypeService;
import cn.itsource.query.BaseQuery;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ArticleTypeServiceImpl implements IArticleTypeService {

    @Autowired
    private ArticleTypeMapper articleTypeMapper;
    @Override
    public PageInfo<ArticleType> pageInfo(BaseQuery baseQuery) {
        PageHelper.startPage(baseQuery.getCurrentPage(), baseQuery.getPageSize());
        List<ArticleType> all = articleTypeMapper.getAllByQuery(baseQuery);
        return new PageInfo<>(all);
    }

    @Override
    public void save(ArticleType user) {
        if (user.getId() == null) {
            articleTypeMapper.save(user);
        }else{
            user.setUpdateTime(new Date());
            articleTypeMapper.update(user);
        }
    }

    @Override
    public void delete(Long id) {
        articleTypeMapper.delete(id);
    }

    @Override
    public void batchDelete(List<ArticleType> users) {
        articleTypeMapper.batchDelete(users);
    }

    @Override
    public List<ArticleType> treeTypes() {
        List<ArticleType> all = articleTypeMapper.getAll();

        List<ArticleType> types = new ArrayList<>();
        //把List集合转为Map集合
        Map<Long, ArticleType> map = all.stream().collect(Collectors.toMap(ArticleType::getId, articleType -> articleType));

        for (ArticleType articleType : all) {
            if(articleType.getParentId()==null){
                types.add(articleType);
            }else{
                ArticleType type = map.get(articleType.getParentId());
                if(type!=null){
                    type.getChildren().add(articleType);
                }

            }
        }

        return types;
    }


}
